<?php
/**
 * Author: xx.com
 */ 
namespace Api\Controller;
use Think\Controller;
use Think\Page;
use Common\Util\dada\client\DadaRequestClient;

class UserController extends BaseController {
    public $userLogic;
    
    /**
     * 析构流函数
     */
    public function  __construct() {   
        parent::__construct();    
        $this->userLogic = new \Home\Logic\UsersLogic();    
    }
	
	/**
	 * base64图片上传
	 * @param $base64_img
	 * @return array
	 */
	public function open_base64_img_upload(){
	    $base64_img = I('base64_img');
		$upload_route = I('upload_route');
		$upload_route_list = C('FILE_BASE_UPLOAD_ROUTE');
		if(!$upload_route_list[$upload_route]){
			$this->returnInfo('-1', '不可用上传路径');
		}
		$upload_object = $this->base64_img_upload($base64_img,$upload_route_list[$upload_route]);
		if($upload_object['status'] == 1){
			$this->returnInfo('1', '图片上传成功',['img_path' => $upload_object['url'],'images_url' => parseMediaUrl($upload_object['url'])]);
		}else{
			$this->returnInfo('-1', $upload_object['msg']);
		}
	    
	}
   
    /**
     *  登录
     */
    public function login(){
        $username = I('username','');
        $password = I('password','');
        $unique_id = I("unique_id"); // 唯一id  类似于 pc 端的session id
        $data = $this->userLogic->app_login($username,$password);
        if($data['status'] != 1)
            exit(json_encode($data));
        $cartLogic = new \Home\Logic\CartLogic();        
        $cartLogic->login_cart_handle($unique_id,$data['result']['user_id']); // 用户登录后 需要对购物车 一些操作               
        exit(json_encode($data));
    }
	
	/**
	 * 微信小程序登录
	 */
	public function miniappLogin(){
		$miniapp_config = C('miniapp');
		$js_code = I('js_code','');
		$nickname = I('nickname','');
		$head_pic = I('head_pic','');
		$coordinate_xy = I('coordinate_xy','');
		$url = "https://api.weixin.qq.com/sns/jscode2session?appid={$miniapp_config['appid']}&secret={$miniapp_config['appsecret']}&js_code={$js_code}&grant_type=authorization_code";
		$result = httpGet($url);
		$result_array = json_decode($result,true);
		// p($result_array);die;
		if(isset($result_array['openid'],$nickname,$head_pic)){
			$openid = $result_array['openid'];
			$session_key = $result_array['session_key'];
			$from = 'miniapp';
			
			$map['openid'] = $openid;
			$map['oauth'] = $from;
			$map['nickname'] = $nickname;
			$map['head_pic'] = $head_pic;
			$map['coordinate_xy'] = $coordinate_xy;
			
			$data = $this->userLogic->thirdLogin($map);
			// p($data);die;
			$cartLogic = new \Home\Logic\CartLogic();  
			$unique_id = $map['openid'];// 临时唯一id  类似于 pc 端的session id
			$cartLogic->login_cart_handle($unique_id,$data['result']['user_id']); // 用户登录后 需要对购物车 一些操作
			exit(json_encode($data));
		}
		exit(json_encode(array('status'=>0,'msg'=>'注册失败','result'=>$result_array)));
	}
	
    /*
     * 第三方登录
     */
	
    public function thirdLogin(){
        $map['openid'] = I('openid','');
        $map['oauth'] = I('from','');
        $map['nickname'] = I('nickname','');
        $map['head_pic'] = I('head_pic',''); 
        $data = $this->userLogic->thirdLogin($map);
		$cartLogic = new \Home\Logic\CartLogic();  
		$unique_id = $map['openid'];// 临时唯一id  类似于 pc 端的session id
		$cartLogic->login_cart_handle($unique_id,$data['result']['user_id']); // 用户登录后 需要对购物车 一些操作
        exit(json_encode($data));
    }

    /**
     * 用户注册
     */
    public function reg(){
        $username = I('post.username','');
        $password = I('post.password','');
        $first_leader = I('post.first_leader','');//邀请码
        
        $unique_id = I('unique_id');
        //是否开启注册验证码机制
        if(check_mobile($username) && TpCache('sms.regis_sms_enable')){
            $code = I('post.code');
            if(empty($code))
                exit(json_encode(array('status'=>-1,'msg'=>'请输入验证码','result'=>'')));
            $check_code = $this->userLogic->sms_code_verify($username,$code,$unique_id);
            if($check_code['status'] != 1)
                exit(json_encode(array('status'=>-1,'msg'=>$check_code['msg'],'result'=>'')));
        }  
        $data = $this->userLogic->reg($username,$password , $password, $first_leader);
        exit(json_encode($data));
    }

    /*
     * 获取用户信息
     */
    public function userInfo(){
        $data = $this->userLogic->get_info($this->user_id);
        exit(json_encode($data));
    }

    /*
     *更新用户信息
     */
    public function updateUserInfo(){
        if(IS_POST){
            //$user_id = I('user_id');
            if(!$this->user_id)
                exit(json_encode(array('status'=>-1,'msg'=>'缺少参数','result'=>'')));
          
            if($_FILES)
            {
                    $upload = new \Think\Upload();// 实例化上传类
                    $upload->maxSize   =    $map['author'] = (1024*1024*3);// 设置附件上传大小 管理员10M  否则 3M
                    $upload->exts      =     array('jpg', 'gif', 'png');// 设置附件上传类型
                    $upload->rootPath  =     './Public/upload/head_pic/'; // 设置附件上传根目录
                    $upload->replace  =     true; // 存在同名文件是否是覆盖，默认为false
                    //$upload->saveName  =   'file_'.$id; // 存在同名文件是否是覆盖，默认为false
                    // 上传文件 
                    $info   =   $upload->upload();  
                    if(!$info) {// 上传错误提示错误信息                                                                                                
                        exit(json_encode(array('status'=>-1,'msg'=>$upload->getError()))); //$this->error($upload->getError());
                    }else{
                        foreach ($info as $key => $value) {
                             $post['head_pic'] = $value['urlpath'];
                         } 
                    }                     
            } 
            I('post.nickname') ? $post['nickname'] = I('post.nickname') : false; //昵称
            I('post.qq') ? $post['qq'] = I('post.qq') : false;  //QQ号码
            (I('post.sex') != '') ? $post['sex'] = I('post.sex') : false;  // 性别
            I('post.birthday') ? $post['birthday'] = I('post.birthday') : false;  // 生日
            I('post.province') ? $post['province'] = I('post.province') : false;  //省份
            I('post.city') ? $post['city'] = I('post.city') : false;  // 城市
            I('post.district') ? $post['district'] = I('post.district') : false;  //地区
            $mobile = I('post.mobile', '', 'trim');
            if (!empty($mobile)) { //手机
                $post['mobile'] = I('post.mobile');
            }
            if(!$this->userLogic->update_info($this->user_id,$post))
                exit(json_encode(array('status'=>-1,'msg'=>'更新失败','result'=>'')));

            exit(json_encode(array('status'=>1,'msg'=>'更新成功','result'=>$post)));

        }
    }
	
	/*
	 * 获取等级列表
	 */
	public function levelList(){
		$user_level_list = M('user_level')->order('level_id asc')->select();
		$json_arr = array('status'=>1,'msg'=>'获取成功','result'=>$user_level_list );
		$json_str = json_encode($json_arr,true);
		exit($json_str);
	}

    /*
     * 修改用户密码
     */
    public function password(){
        if(IS_POST){
            if(!$this->user_id){
                exit(json_encode(array('status'=>-1,'msg'=>'缺少参数','result'=>'')));
            }
            $user_id = $this->user_id;
            $old_password = I('post.old_password');
            $new_password = I('post.password');
            $mobile = I('post.mobile');
            $unique_id = I('post.unique_id');
            $checkCode = I('check_code');   //验证码
            $data = $this->userLogic->passwordForApp($user_id,$old_password,$new_password,$mobile,$unique_id); // 修改密码
            if ($data['result'] == '1') {
                $this->returnInfo('1','修改密码成功');
            }else{
                $this->returnInfo('-1','修改密码失败');
            }
        }
    }
    
    /**
     * @add by wangqh APP端忘记密码
     * 忘记密码
     */
    public function forgetPassword(){
        $password = I('password');
        $mobile = I('mobile');
        $unique_id = I('unique_id');        
        $checkCode = I('check_code');   //验证码

        // //验证原密码
        //  if($is_update && ($user['password'] != '' && $old_password != $user['password']))
        //     return array('status'=>-1,'msg'=>'原密码有误','result'=>'');

        if(!check_mobile($mobile)){
            exit(json_encode(array('status'=>-1,'msg'=>'手机号码格式不正确','result'=>'')));
        }
        
        //获取时间配置
        $sms_time_out = tpCache('sms.sms_time_out');
        $sms_time_out = $sms_time_out ? $sms_time_out : 120;
        //120秒以内不可重复发送
     
        $data = M('sms_log')->where(array('mobile'=>$mobile,'session_id'=>$unique_id))->order('id DESC')->find();
        if(!$data){
            exit(json_encode(array('status'=>-1,'msg'=>'短信验证码错误','result'=>'')));
        }else if((time() - $data['add_time']) > $sms_time_out ){
            //验证码过期
            exit(json_encode(array('status'=>-1,'msg'=>'短信验证码过期','result'=>'')));
        }
            
        $user = M('users')->where("mobile = '$mobile'")->find();
        if(empty($user)){
            exit(json_encode(array('status'=>-1,'msg'=>'该手机号码没有关联账户','result'=>'')));
        }else{
            //修改密码
            $pdata['password'] = $password;
            M('users')->where("user_id=".$user['user_id'])->save($pdata);
            exit(json_encode(array('status'=>1,'msg'=>'密码已重置','result'=>'')));
        }
    }
    

    /**
     * 获取收货地址
     */
    public function getAddressList(){
        $user_id = $this->user_id;
        if(!$user_id){
            $this->returnInfo('-1','缺少参数');
        }
        $where['user_id'] = $user_id;
        $address = M('user_address')->where($where)->select();
        $addresslists = $this->getAddressInfo($address);
        if(!$addresslists)
            $this->returnInfo('1','没有数据',[]);
            $this->returnInfo('1','获取成功',$addresslists);
    }
	
	/**
	 * 获取指定收货地址
	 */
	public function getAddressData(){
	    $user_id = $this->user_id;
	    if(!$user_id){
	        $this->returnInfo('-1','缺少参数');
	    }
		$address_id = I('address_id',0);
	    $where['user_id'] = $user_id;
	    $where['address_id'] = $address_id;
	    $address = M('user_address')->where($where)->select();
	    $addresslists = $this->getAddressInfo($address);
	    if(!$addresslists)
	        $this->returnInfo('1','没有数据',[]);
	        $this->returnInfo('1','获取成功',$addresslists[0]);
	}

    /*
     * 添加地址
     */
    public function addAddress(){
        if(!$this->user_id) exit(json_encode(array('status'=>-1,'msg'=>'缺少参数','result'=>'')));
        $address_id = I('post.address_id',0);
        $post = I('post.');
        $where['region_code'] = $post['province'];
        $post['province_name'] = M('region')->field('region_name')->where($where)->find();
        $post['province_name'] = $post['province_name']['region_name'];
        unset($where);
        $where['region_code'] = $post['city'];
        $post['city_name'] = M('region')->field('region_name')->where($where)->find();
        $post['city_name'] = $post['city_name']['region_name'];
        unset($where);
        $where['region_code'] = $post['district'];
        $post['district_name'] = M('region')->field('region_name')->where($where)->find();
        $post['district_name'] = $post['district_name']['region_name'];
        $data = $this->userLogic->add_address($this->user_id,$address_id,$post); // 获取用户信息
        exit(json_encode($data));
    }



    /*
     * 地址删除
     */
    public function del_address(){
        $id = I('address_id');
        if(!$this->user_id) exit(json_encode(array('status'=>-1,'msg'=>'缺少参数','result'=>'')));
        $address = M('user_address')->where("address_id = $id")->find();
        $row = M('user_address')->where(array('user_id'=>$this->user_id,'address_id'=>$id))->delete();                
        // 如果删除的是默认收货地址 则要把第一个地址设置为默认收货地址
        if($address['is_default'] == 1)
        {
            $address = M('user_address')->where("user_id = {$this->user_id}")->find();
            if (!empty($address)) {
                M('user_address')->where("address_id = {$address['address_id']}")->save(array('is_default'=>1));
            }          
            
        }        
        //@mobify by wangqh 
        if($row)
           exit(json_encode(array('status'=>1,'msg'=>'删除成功','result'=>''))); 
        else
           exit(json_encode(array('status'=>-1,'msg'=>'删除失败','result'=>''))); 
    } 
    /*
     * 设置默认收货地址
     */
    public function setDefaultAddress(){
//        $user_id = I('user_id',0);
        if(!$this->user_id) exit(json_encode(array('status'=>-1,'msg'=>'缺少参数','result'=>'')));
        $address_id = I('address_id',0);
        $data = $this->userLogic->set_default($this->user_id,$address_id); // 获取用户信息
        if(!$data)
            exit(json_encode(array('status'=>-1,'msg'=>'操作失败','result'=>'')));
        exit(json_encode(array('status'=>1,'msg'=>'操作成功','result'=>'')));
    }


    //获取优惠券列表
    public function getCouponList(){
        $nowTime = date('Y-m-d H:i:s');
        $user_id = $this->user_id;
        $type = I('type');   // 1已使用。2 未使用。3 已过期
        if ($type == 1) {
            $data = M('coupon_list as cl')->field('sum(c.money) as money,c.use_start_time,c.use_end_time')->where("cl.uid=$user_id and cl.use_time>0")->join('ln_coupon as c on cl.type=c.type')->select();
        }elseif($type == 2){
            $data1 = M('coupon_list as cl')->field('c.use_end_time')->where("cl.uid=$user_id")->join('ln_coupon as c on cl.type=c.type')->select();
            foreach ($data1 as $key => $value) {
                $where['cl.uid'] = $user_id;
                $where['c.use_end_time'] = $value['use_end_time'];
                $where['cl.use_time'] = 0;
                if (strtotime($nowTime)<$value['use_end_time']) {
                    $data = M('coupon_list as cl')->field('sum(c.money) as money,c.use_start_time,c.use_end_time')->where($where)->join('ln_coupon as c on cl.type=c.type')->select();
                }
            }
        }else{
            $data1 = M('coupon_list as cl')->field('c.use_end_time')->where("cl.uid=$user_id")->join('ln_coupon as c on cl.type=c.type')->select();
            foreach ($data1 as $key => $value) {
                $where['cl.uid'] = $user_id;
                $where['c.use_end_time'] = $value['use_end_time'];
                if (strtotime($nowTime)>$value['use_end_time']) {
                    $data = M('coupon_list as cl')->field('sum(c.money) as money,c.use_start_time,c.use_end_time')->where($where)->join('ln_coupon as c on cl.type=c.type')->select();
                    }
                }
        }
        $this->returnInfo(1,'获取成功',$data);
    }

    //兑换券排行榜
    public function rankingList(){
        $token = I('token');
        $map['token'] = $token;
        $user_id = M('users')->field('user_id,oauth')->where($map)->find();
        $user_id = $user_id['user_id'];
        $where['uid'] = $user_id;

        $list = M('users')->field('user_id,nickname,head_pic,pay_points,oauth,coupon_price')->limit(1000)->order('pay_points desc')->select();
        foreach ($list as $key => &$value) {
            $value['pay_points'] = $value['pay_points']?$value['pay_points']:0;
            $value['coupon_price'] = $value['pay_points'];
            $value['head_pic'] = parseMediaUrl($value['head_pic']);
        }
        $this->returnInfo(1,'获取成功',$list);
    }




    /*
     * 获取商品收藏列表
     */
    public function getGoodsCollect(){
//        $user_id = I('user_id',0);
        //if(!$this->user_id) exit(json_encode(array('status'=>-1,'msg'=>'缺少参数','result'=>'')));
        $data = $this->userLogic->get_goods_collect($this->user_id);
        // foreach($data['result'] as &$r){

        // }
        unset($data['show']);
        exit(json_encode($data));
    }

    /*
     * 用户订单列表
     */
    public function getOrderList(){
       // $user_id = I('user_id',0);
        $type = I('post.type','');
        if(!$this->user_id) exit(json_encode(array('status'=>-1,'msg'=>'缺少参数','result'=>'')));
    // 'WAITPAY'=>' AND pay_status = 0 AND order_status = 0 AND pay_code !="cod" ', //订单查询状态 待支付
    // 'WAITSEND'=>' AND (pay_status=1 OR pay_code="cod") AND shipping_status !=1 AND order_status in(0,1) ', //订单查询状态 待发货
    // 'WAITRECEIVE'=>' AND shipping_status=1 AND order_status = 1 ', //订单查询状态 待收货    
    // 'WAITCCOMMENT'=> ' AND order_status=2 ', // 待评价 确认收货     //'FINISHED'=>'  AND order_status=1 ', //订单查询状态 已完成 
    // 'FINISH'=> ' AND order_status = 4 ', // 已完成
    // 'CANCEL'=> ' AND order_status = 3 ', // 已取消
    // 'CANCELLED'=> 'AND order_status = 5 ',//已作废
        $map = " user_id = {$this->user_id} ";        
        $map = $type ? $map.C($type) : $map;   
        $map .= "AND parent_sn !='0'";
        if(I('type') )
        $count = M('order')->where($map)->count();
        $Page       = new \Think\Page($count,10);
        $show = $Page->show();
        $order_str = "order_id DESC";

        #下面这句话有个卵子用
        // $cart_shop = M('order as o')->where("o.user_id=$this->user_id and o.parent_sn!='0'")->group('o.shop_id')->join('ln_shop as s on s.id=o.shop_id','left')->field('o.shop_id,s.shop_name,s.shop_head_img')->select();
        // foreach ($cart_shop as $key => $value) 
        // {
        //     $cart_shop[$key]['shop_id'] = $value['shop_id']?$value['shop_id']:0;
        // }
        $order_list = M('order')->order($order_str)->where($map)->limit($Page->firstRow.','.$Page->listRows)->select();

        //获取订单商品
        foreach($order_list as $k => &$v)
        {
            $v = set_btn_order_status($v);  // 添加属性  包括按钮显示属性 和 订单状态显示属性
            $rebate_status = M('rebate_log')->field('status')->where(array('order_id'=>$v['order_id']))->find();
            $v['rebate_status'] = $rebate_status['status'] ? $rebate_status['status'] : 0;
            $shop_info = M('shop')->field('id as shop_id,shop_name,shop_head_img')
            ->where(array('id'=>$v['shop_id']))
            ->cache(120)
            ->find();
            $v['shop_name'] = $shop_info ? $shop_info['shop_name'] : "";
            $v['shop_head_img'] = $shop_info ? parseMediaUrl($shop_info['shop_head_img']) : "";            
            $v['province'] = $v['province'] ?$v['province']:0;
            $v['city'] =  $v['city']?$v['city']:0;
            $v['district'] = $v['district']?$v['district']:0;
            $v['twon'] = $v['twon']?$v['twon']:0;

            $v['province_name'] = $v['province_name']?$v['province_name']:"";
            $v['city_name'] =  $v['city_name']?$v['city_name']:"";
            $v['district_name'] = $v['district_name']?$v['district_name']:"";
            $v['twon_name'] = $v['twon_name']?$v['twon_name']:"";

            $is_allow_drawback = 0;
            $v['drawback_btn'] = 0;
            if($v['is_drawback'] == 0){
                if($v['order_type'] == 1){
                    $allow_day = tpCache('shopping.drawback_time_normal');
                    if(($v['confirm_time'] > 0) && ($v['confirm_time'] + $allow_day * 3600 > time())){
                        $is_allow_drawback = 1;
                    }
                }else if($v['order_type'] == 2){
                    $allow_day = tpCache('shopping.drawback_time_spec');
                    if(($v['confirm_time'] > 0) && ($v['confirm_time'] + $allow_day * 3600 > time())){
                        $is_allow_drawback = 1;
                    }
                }
            }else{
                $v['order_status_desc'] = $v['is_drawback'] == 1 ? '待处理': '已处理';
            }

            $data = $this->userLogic->get_order_goods($v['order_id'], $is_allow_drawback );
            $v['goods_list'] = $data['result'];
            //申请退款信息
            //$drawback = M('drawback')->where(array('order_id'=>$v['order_id']))->select();
            $v['drawback_btn'] = $is_allow_drawback; //退款按钮
        }
        exit(json_encode(array('status'=>1,'msg'=>'获取成功','result'=>$order_list)));
    }


     /**
     * 按照定单状态查询定单的数量
     * @param $where 查询条件
     * @return array 返回以定单状态为下标, 定单数量为值的数组
     */
    public function getOrderStat($where){
        $where['parent_sn'] = array('neq', '0');
        $where['status'] = array('eq', 1);
        $orderStat = M('order')->where($where)->group('order_status')->getField('order_status, count(*) as count');
        // echo array_sum($orderStat);
        return $orderStat;
    }


      //获取某一字段的统计
    public function getOrderCount($where, $field) {
        $where['status'] =  array('eq', 0);
        $where['parent_sn'] = array('neq', '0');
        $res =  M('order')->where($where)->count($field);
        return $res;
    }


    /*
     * 获取订单详情
     */
    public function getOrderDetail(){
        //$user_id = I('user_id',0);
        if(!$this->user_id) exit(json_encode(array('status'=>-1,'msg'=>'缺少参数','result'=>'')));
        $id = I('id');
        if(I('id')){
            $map['order_id'] = $id;
        }else{
            $map['order_sn'] = I('sn');
        }
        $map['user_id'] = $this->user_id;
        $order_info = M('order')->where($map)->find();
        if(!$order_info){
            exit(json_encode(array('status'=>-1,'msg'=>'订单信息有误','result'=>'')));
        }
		
        if($order_info['pay_status'] && !$order_info['pay_name']){
            $order_info['pay_name'] = '其他支付方式';
        }
        $addresslist = M('UserAddress')->where("user_id = {$this->user_id}")->find();
        $order_info['province_name'] = $addresslist['province_name'];
        $order_info['city_name']     = $addresslist['city_name'];
        $order_info['district_name'] = $addresslist['district_name'];
        $order_info['twon_name']     = $addresslist['twon_name'];
        $order_info = set_btn_order_status($order_info);  // 添加属性  包括按钮显示属性 和 订单状态显示属性
        if(!$this->user_id > 0)
            exit(json_encode(array('status'=>-1,'msg'=>'参数有误','result'=>'')));
        if(!$order_info){
            exit(json_encode(array('status'=>-1,'msg'=>'订单不存在','result'=>'')));
        }
		// 修复以前不严谨
		$id = $order_info['order_id'];
        $where['order_id'] = $id;
        $invoice_no = M('DeliveryDoc')->field('invoice_no,create_time')->where($where)->order('id desc')->find();
        if (!$invoice_no) {
            $order_info['invoice_no']="";//$this->returnInfo('-1','暂无物流信息');exit();
        }else{
            $order_info['invoice_no']=$invoice_no['invoice_no']?$invoice_no['invoice_no']:"";
        }

        $is_allow_drawback = 0;
        if($order_info['is_drawback'] == 0){
            if($order_info['order_type'] == 1){
                $allow_day = tpCache('shopping.drawback_time_normal');
                if(($order_info['confirm_time'] > 0) && ($order_info['confirm_time'] + $allow_day *  3600 > time())){
                    $is_allow_drawback = 1;
                }
            }else if($order_info['order_type'] == 2){
                $allow_day = tpCache('shopping.drawback_time_spec');
                if(($order_info['confirm_time'] > 0) && ($order_info['confirm_time'] + $allow_day *  3600 > time())){
                    $is_allow_drawback = 1;
                }
            }
        }

        $order_info['exp_fee'] = $order_info['order_type'] == 2
            ? (tpCache('shopping.drawback_exp_fee') ? tpCache('shopping.drawback_exp_fee') : 0):0;        //获取订单商品
        $data = $this->userLogic->get_order_goods($order_info['order_id'], $is_allow_drawback);
        $order_info['goods_list'] = $data['result'];
        $drawback_info = M('drawback')->where(array('order_id'=>$id))->find();
        if($drawback_info){
            $order_info['drawback_btn'] = 0;
            $drawback_info['img'] = unserialize($drawback_info['img']);
            if(!empty($drawback_info['img']))
            {
                foreach($drawback_info['img'] as &$item)
                {
                    $item = parseMediaUrl($item);
                }
            }else{
                $drawback_info['img'] = [];
            }
            if($drawback_info['status'] == 0){
                $drawback_info['real_money'] = $drawback_info['money'];
            }
        }else{
            $drawback_info = array();
            if($is_allow_drawback == 1){
                $order_info['drawback_btn'] = 1;
            }
        }

        $order_info['drawback'] = $drawback_info;
        exit(json_encode(array('status'=>1,'msg'=>'获取成功','result'=>$order_info)));
    }

    /**
     * 取消订单
     */
    public function cancelOrder(){
        $id = I('order_id');
        if(!$this->user_id > 0 || !$id > 0)
            $this->returnInfo('-1','参数有误','');
        $data = $this->userLogic->cancel_order($this->user_id,$id);
        exit(json_encode($data));
    }

     /**
     * 订单删除
     * @param int $id 订单id
     */
    public function delete_order(){
        $this->deleteOrder();
    }

    /**
     * 订单删除
     * @param int $id 订单id
     */
    public function deleteOrder(){
        $user_id = $this->user_id;
        if ($user_id) {
            $order_id = I('order_id');
            M()->startTrans();
            $order = M('order')
            ->where([
                'order_id'=>$order_id,
                'user_id'=>$user_id,
            ])->field("order_id,pay_status,order_sn,is_groupbuy")->find();
            
            if(!$order)
            {
                $this->returnInfo('-1','订单不存在');
            }

            if($order['pay_status'])
            {
                $this->returnInfo('-1','订单当前状态不允许删除');
            }

            $a = M('order')->where(array('order_id'=>$order_id))->delete();
            $b = M('order_goods')->where(array('order_id'=>$order_id))->delete();
            $c = true;
            if($order['is_groupbuy'])
            {
                $c = M('group_order')->where(array('order_sn'=>$order['order_sn']))->delete();
            }

            if($a && $b && $c){
                M()->commit();
                $this->returnInfo('1','删除订单成功');
            }else{
                M()->rollback();
                $this->returnInfo('-1','订单删除失败',[
                    "delete_order" => $a,
                    "delete_order_goods" => $b,
                    "delete_grouporder" => $c,
                ]);
            }
        }else{
            $this->returnInfo('-1','参数有误');
        }
        
    }

    
    
    /**
     * 发送手机注册验证码
     * http://www.xx.com/index.php?m=Api&c=User&a=send_sms_reg_code&mobile=13800138006&unique_id=123456
     */
    public function send_sms_reg_code(){
        $mobile = I('mobile');     
        $unique_id = I('unique_id');
        if(!check_mobile($mobile))
            exit(json_encode(array('status'=>-1,'msg'=>'手机号码格式有误')));
        $code =  rand(1000,9999);
        //验证是否已经注册

        if(get_user_info($mobile,1)||get_user_info($mobile,2)){
            exit(json_encode(array('status'=>-1,'msg'=>'手机号码已注册')));
        }

        //$send = $this->userLogic->sms_log($mobile,$code,$unique_id);
        $send = $this->userLogic->sms_liuniu_log($mobile,$code,$unique_id);
        if($send['status'] != 1)
            exit(json_encode(array('status'=>-1,'msg'=>$send['msg'])));
        exit(json_encode(array('status'=>1,'msg'=>'验证码已发送，请注意查收')));
    }    

    //发送验证码
    public function send_validate_code(){
        $send = I('send');
        $unique_id = I('unique_id');
        if(!check_mobile($send))
            exit(json_encode(array('status'=>-1,'msg'=>'手机号码格式有误')));
        $code =  rand(1000,9999);
        $res = $this->userLogic->sms_liuniu_log($send, $code, $unique_id);
        if($res['status'] != 1)
            exit(json_encode(array('status'=>-1,'msg'=>$res['msg'])));
        exit(json_encode(array('status'=>1,'msg'=>'验证码已发送，请注意查收')));
    }

    /*
    * 手机验证
    */
    public function mobile_validate(){        
        $user_info = $this->userLogic->get_info($this->user_id); //获取用户信息
        $user_info = $user_info['result'];
        $config = F('sms','',TEMP_PATH);
        if(!$user_info['user_id'] > 0)
            $this->returnInfo('-1','参数有误',"");
        if (!empty($user_info['mobile'])) {
            $sms_time_out = $config['sms_time_out'];
            $mobile = I('post.mobile');
            $old_mobile = I('post.old_mobile','');
            $code = I('post.code');
            $unique_id = I('post.unique_id');
            $data = M('sms_log')->where(array('mobile'=>$mobile,'session_id'=>$unique_id))->order('id DESC')->find();
            if(!$data){
                $this->returnInfo('-1','短信验证码错误',"");
            }else if((time() - $data['add_time']) > $sms_time_out ){
                    //验证码过期
                $this->returnInfo('-1','短信验证码过期',"");
            }   

            //检查原手机是否正确
            if($user_info['mobile_validated'] == 1 && $mobile != $user_info['mobile'])
                $this->returnInfo('-1','原手机号码错误',"");
             //检查原手机是否正确
            if($user_info['mobile_validated'] == 1 && $old_mobile != $user_info['mobile'])
                $this->returnInfo('-1','原手机号码错误',"");
            //验证手机和验证码
            if($data['mobile'] != $old_mobile )
            {
                $this->returnInfo('-1','原手机号不匹配',"");
            }
            if($data['code'] != $code )
            {
                $this->returnInfo('-1','验证码错误',"");
            }
        }else{
            $sms_time_out = $config['sms_time_out'];
            $mobile = I('post.mobile');
            $old_mobile = I('post.old_mobile','');
            $code = I('post.code');
            $unique_id = I('post.unique_id');
            $data = M('sms_log')->where(array('mobile'=>$mobile,'session_id'=>$unique_id))->order('id DESC')->find();
            if(!$data){
                $this->returnInfo('-1','短信验证码错误',"");
            }
            if((time() - $data['add_time']) > $sms_time_out ){//验证码过期
                $this->returnInfo('-1','短信验证码过期',"");
            }
 
        }

        try{
            $changeMobile = $this->userLogic->update_email_mobile($mobile,$this->user_id,2);
        }catch(\Exception $e)
        {
            $this->returnInfo($e->getCode(),$e->getMessage(),"");
        }
        
        if(!$changeMobile)
            $this->returnInfo('-1','手机号更换失败',"");

        $this->returnInfo('1','绑定成功',"");
    }




    /**
     *  收货确认
     */
    public function  orderConfirm (){
        $id = I('order_id',0);
        //$user_id = I('user_id',0);
        if(!$this->user_id || !$id)
            exit(json_encode(array('status'=>-1,'msg'=>'参数有误','result'=>'')));
        $data = confirm_order($id,$this->user_id,"用户主动确认收货");
        if($data['status']){
            // 根据order表查看消费记录 给他会员等级升级 修改他的折扣 和 总金额zn
            update_user_level($this->user_id);
        }
        //获取用户等级信息
        $userInfo = $this->userLogic->get_info($this->user_id);
        $data['result'] = array('level_name'=>$userInfo['result']['level_name'], 'level'=>$userInfo['result']['level']);
        exit(json_encode($data));
    }
    
	/**
	 * base64图片上传
	 * @param $base64_img
	 * @return array
	 */
	private static function base64_img_upload($base64_img,$upload_route){
	    $base64_img = trim($base64_img);
	    $time = time().get_rand_str(6,0,0);

	    $date = date('Y');
	    $date1 = date('m-d');
	    // $up_dir = './Public/upload/head_pic/'.$date.'/'.$date1.'/';
		$up_dir = $upload_route.$date.'/'.$date1.'/';
	    if(!file_exists($up_dir)){
	        mkdir($up_dir,0777,true);
	    }
	    if(preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_img, $result)){
	        $type = $result[2];
	        if(in_array($type,array('pjpeg','jpeg','jpg','gif','bmp','png'))){
	            $new_file = $up_dir.$time.'.'.$type;
	            //var_dump($new_file);exit;
	            if(file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_img)))){
	                $img_path = str_replace('./', '/', $new_file);
	                return array('status' => 1, 'msg' => "图片上传成功", 'url' => $img_path);
	            }
	            return array('status' => 2, 'msg' => "图片上传失败");
	        }
	        //文件类型错误
	        return array('status' => 4, 'msg' => "文件类型错误");
	    }
	    //文件错误
	    return array('status' => 3, 'msg' => "文件错误");
	}
    
    /*
     *添加评论
     */
    public function add_comment(){
		// p(1);die;
		// p($_FILES);die;
		$urlpath = I("urlpath");
		// p($urlpath);die;
        if(is_array ($urlpath))
        {
			$upload_route = './Public/upload/comment/';
			foreach($urlpath as $k => $v){
				$return = $this->base64_img_upload($v,$upload_route);
				if($return['status'] == 1){
					$comment_img[] = $return['url'];
				}
			}
			// p($comment_img);die;
			$add['img'] = serialize($comment_img);// 上传的图片文件
        }
		
        $order_id = I("order_id");
        $goods_id = I("goods_id"); 
        $unique_id = I("unique_id"); // 唯一id  类似于 pc 端的session id
		
        $user_info = M('users')->where("user_id = {$this->user_id}")->find();
		// p($add);die;
        $add['order_id'] = $order_id;    
        $add['goods_id'] = $goods_id;
        $add['email'] = '';
        $add['username'] = empty($user_info['nickname']) ? '用户'.$this->user_id : $user_info['nickname'] ; //用户nickname为空，取用户id
        $add['service_rank'] = I('service_rank');
        $add['deliver_rank'] = I('deliver_rank');
        $add['goods_rank'] = I('goods_rank');
		$add['is_anonymous'] = I('is_anonymous');
        $add['content'] = I('content');
        $add['add_time'] = time();
        $add['ip_address'] = $_SERVER['REMOTE_ADDR'];
        $add['user_id'] = $this->user_id; 
		// p($add);die;
        //添加评论
        $row = $this->userLogic->add_comment($add);
        exit(json_encode($row));
    }  
    
    /*
     * 余额明细
     */
    public function account(){
        //获取账户资金记录
        $data = $this->userLogic->get_account_log($this->user_id,1);
        $account_log = $data['result'];
        $this->returnInfo(1,'获取成功',$account_log);
        // exit(json_encode(array('status'=>1,'msg'=>'获取成功','result'=>$account_log)));
    } 


    //积分明细
    public function conchDetail(){
        $data = $this->userLogic->get_account_log($this->user_id,2);
        $account_log = $data['result'];
		foreach($account_log as $k=>&$v){
			$v['change_time_str'] =  date('Y-m-d',$v['change_time']);
		}
		// p($account_log);die;
        $this->returnInfo(1,'获取成功',$account_log);
        // $user_id = $this->user_id;
        // $userId = M('users')->field("user_id")->where("first_leader=$user_id")->select();
        // foreach ($userId as $key => $value) {
        //     $user_ids[] = $value['user_id'];
        // }
        // $user_id = array($user_id);
        // $ids = array_merge($user_id,$user_ids);
        // $result=[];
        // foreach ($ids as $key => $value) {
        //     $data = M('account_log as a')
        //           ->field("a.user_id,u.nickname,a.pay_points,a.change_time")
        //           ->where("a.user_id=$value and a.pay_points!=0")
        //           ->join("ln_users as u on u.user_id=a.user_id")
        //           ->select();
        //     foreach ($data as $key1 => $value1) {
        //         $result[$key1]['msg'] = "来自".$value1['nickname']."的收益提成";
        //         $result[$key1]['pay_points'] = $value1['pay_points'];
        //         $result[$key1]['change_time'] = $value1['change_time'];
        //     }

        // }
        // $this->returnInfo('1','获取成功',$result);
    }


    /**
     * 退换货列表
     */
    public function return_goods_list()
    {        
        
        $unique_id = I("unique_id"); // 唯一id  类似于 pc 端的session id
       // $user_id = I('user_id'); // 用户id       
        $count = M('return_goods')->where("user_id = {$this->user_id}")->count();        
        $page = new \Think\Page($count,4);
        $list = M('return_goods')->where("user_id = {$this->user_id}")->order("id desc")->limit("{$page->firstRow},{$page->listRows}")->select();
        $goods_id_arr = get_arr_column($list, 'goods_id');
        if(!empty($goods_id_arr))
            $goodsList = M('goods')->where("goods_id in (".  implode(',',$goods_id_arr).")")->getField('goods_id,goods_name');        
        foreach ($list as $key => $val)
        {
            $val['goods_name'] = $goodsList[$val[goods_id]];
            $list[$key] = $val;
        }
        //$this->assign('page', $page->show());// 赋值分页输出                    	    	
        exit(json_encode(array('status'=>1,'msg'=>'获取成功','result'=>$list)));
    }    
    
    
    /**
     *  售后 详情
     */
    public function return_goods_info()
    {
        $id = I('id',0);
        $return_goods = M('return_goods')->where("id = $id")->find();
        if($return_goods['imgs'])
            $return_goods['imgs'] = explode(',', $return_goods['imgs']);        
        $goods = M('goods')->where("goods_id = {$return_goods['goods_id']} ")->find();                
        $return_goods['goods_name'] = $goods['goods_name'];
        exit(json_encode(array('status'=>1,'msg'=>'获取成功','result'=>$return_goods)));
    }    
    
    
    /**
     * 申请退货状态
     */
    public function return_goods_status()
    {
        $order_id = I('order_id',0);        
        $goods_id = I('goods_id',0);

        if(!$order_id || !$goods_id){
            exit(json_encode(array('status'=>-1,'msg'=>'参数有误','result'=>'')));
        }
        $where['order_id'] = $order_id;
        $where['goods_id'] = $goods_id;

        $spec_key = I('spec_key','');
        if($spec_key){
            $where['spec_key'] = $spec_key;
        }
        $where['status'] = array('in','0,1');

        $return_goods = M('return_goods')->where($where)->find();

        if($return_goods){
            exit(json_encode(array('status'=>2,'msg'=>'已经提交过申请','result'=>$return_goods['id'])));
        } else{
            exit(json_encode(array('status'=>1,'msg'=>'可以去申请退货','result'=>-1)));
        }

    }
    /**
     * 申请退货
     */
    public function return_goods()
    { 
        $unique_id = I("unique_id"); // 唯一id  类似于 pc 端的session id
        //$user_id = I('user_id'); // 用户id              
        $order_id = I('order_id',0);
        $order_sn = I('order_sn',0);
        $goods_id = I('goods_id',0);
        $type = I('type',0); // 0 退货  1为换货 2为退款
        $reason = I('reason',''); // 问题描述
        $spec_key = I('spec_key');

        //if(empty($order_id) || empty($order_sn) || empty($goods_id)|| empty($this->user_id)|| empty($type)|| empty($reason))    //empty($type) == 1
        if(empty($order_id) || empty($order_sn) || empty($goods_id)|| empty($this->user_id)|| empty($reason))
            exit(json_encode(array('status'=>-1,'msg'=>'参数不齐!')));
        
        $c = M('order')->where("order_id = $order_id and user_id = {$this->user_id}")->count();
        if($c == 0)
        {
             exit(json_encode(array('status'=>-3,'msg'=>'非法操作!')));           
        }         
        
        $return_goods = M('return_goods')->where("order_id = $order_id and goods_id = $goods_id and spec_key = '$spec_key' and status in(0,1)")->find();            
        if(!empty($return_goods))
        {
            exit(json_encode(array('status'=>-2,'msg'=>'已经提交过退货申请!')));
        }       
    	if(IS_POST){
            // 晒图片
            if($_FILES){
                $upload = new \Think\Upload();// 实例化上传类
                $upload->maxSize   =    $map['author'] = (1024*1024*3);// 设置附件上传大小 管理员10M  否则 3M
                $upload->exts      =    array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
                $upload->rootPath  =    './Public/upload/return_goods/'; // 设置附件上传根目录
                $upload->replace   =    true; // 存在同名文件是否是覆盖，默认为false
                //$upload->saveName  =  'file_'.$id; // 存在同名文件是否是覆盖，默认为false
                // 上传文件
                $upinfo  =  $upload->upload();
                if(!$upinfo) {// 上传错误提示错误信息
                    $this->error($upload->getError());
                }else{
                    foreach($upinfo as $file){        
                        $return_imgs[]= $file['urlpath']; 
                    }
                    $data['imgs'][] = implode(',', $return_imgs);// 上传的图片文件

                }
            }
            #要记录shop_id
            $goods_info = M('goods')->where([
                "goods_id" => $goods_id
            ])->field('goods_id,shop_id')->find();
            $data['shop_id'] = $goods_info ? $goods_info['shop_id'] : 0;
            $data['order_id'] = $order_id; 
            $data['order_sn'] = $order_sn; 
            $data['goods_id'] = $goods_id; 
            $data['addtime'] = time(); 
            $data['user_id'] = $this->user_id;            
            $data['type'] = $type; // 服务类型  退货 或者 换货
            $data['reason'] = $reason; // 问题描述            
            $data['spec_key'] = $spec_key; // 商品规格                      
            $return_id = M('return_goods')->add($data);
            if($return_id) {
                //申请退货，取消返现
                $result_info = M('rebate_log')->where(array('order_id' => $order_id))->setField('status', 4);
                //修改商品申请退货状态
                $order_goods = array(
                    'apply_return' => 1,
                    'is_comment'   => 2,    //申请退换货，不允许评论
                );
                $order_goods_info = M('order_goods')->where(array('order_id' => $order_id, 'goods_id' => $goods_id))->save($order_goods);
                $this->returnInfo(1,'申请成功,客服第一时间会帮你处理!');
            } else {
                $this->returnInfo(-1,'申请失败!');
            }
        }     
    }  

    // base64上传头像
    public function editavator(){
        if(!$this->user_id)
                exit(json_encode(array('status'=>-1,'msg'=>'缺少参数','result'=>'')));
        $img = I('avatar');
        
        $return = $this->img_upload($img);
        if($return['status']==1){
            $data['user_id'] = $this->user_id;  
            $data['head_pic'] = '/Public/upload/'.$return['url'];
            M('users')->where('user_id=' .$data['user_id'])->save($data);
            $this->returnInfo($return['status'],$return['msg'],parseMediaUrl($data['head_pic']));
        }else{
            $this->returnInfo($return['status'],$return['msg']);
        }  
    }

    
    
    /**
     * base64图片上传
     * @param $base64_img
     * @return array
     */
    private static function img_upload($base64_img){
        $base64_img = trim($base64_img);
        $time = time();
        $date = date('Y');
        $date1 = date('m-d');
        $up_dir = './Public/upload/head_pic/'.$date.'/'.$date1.'/';
     
        if(!file_exists($up_dir)){
            mkdir($up_dir,0777,true);
        }
        if(preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_img, $result)){
            $type = $result[2];
            if(in_array($type,array('pjpeg','jpeg','jpg','gif','bmp','png'))){
                $new_file = $up_dir.$time.'.'.$type;
                //var_dump($new_file);exit;
                if(file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_img)))){
                    $img_path = str_replace('./Public/upload/', '', $new_file);
                    return array('status' => 1, 'msg' => "图片上传成功", 'url' => $img_path);
                }
                return array('status' => 2, 'msg' => "图片上传失败");
            }
            //文件类型错误
            return array('status' => 4, 'msg' => "文件类型错误");
        }
        //文件错误
        return array('status' => 3, 'msg' => "文件错误");
    }
    /**
     * 用户提现申请
     */
    public function withdrawals(){
        $data['user_id'] = $this->user_id;      //获取用户的Id
        $data['money'] = I('post.money', 0, 'floatval');                     //获取用户的提现金额
        $data['bank_name'] = I('post.bank_name', '', 'trim');             //银行名称  如:支付宝,农业银行,工商银行等
        $data['account_bank'] = I('post.account_bank', '', 'trim');       //收款账号
        $data['account_name'] = I('post.account_name', '', 'trim');       //开户名
        foreach($data as $key=>$val){
            if(empty($val)){
                switch ($key){
                    case 'user_id' : $message = '用户信息有误';break;
                    case 'money' : $message = '提现金额有误';break;
                    case 'bank_name' : $message = '银行名称不能为空';break;
                    case 'account_bank' : $message = '收款账号不能为空';break;
                    case 'account_name' : $message = '开户姓名不能为空';break;
                }
                exit(json_encode(array('status'=>-1,'msg'=>$message)));
            }
        }
        $data['create_time'] = time();  
        $distribut_min = tpCache('distribut.min');          //最少提现额度
        if($data['money'] < $distribut_min)
            exit(json_encode(array('status'=>-1,'msg'=>'每次最少提现额度'.$distribut_min)));
        $user = M('users')->where("user_id = {$data['user_id']}")->find();
        if($data['money'] > $user['user_money'])
            exit(json_encode(array('status'=>-1,'msg'=>'你最多可提现'.$user['user_money'].'账户余额')));
        if(M('withdrawals')->add($data))
            exit(json_encode(array('status'=>1,'msg'=>'提交申请成功')));
        else
            exit(json_encode(array('status'=>-1,'msg'=>'提交失败,请联系客服人员!')));     
    } 
    /**
     * 用户提现充值数据列表
     */
    public function userMoneyRecord(){
        //获取用户ID
        $user_id = $this->user_id;
        $page = I('post.p',0,'intval');
        if(!($page>0 && $user_id>0))        
            exit(json_encode(array('status'=>-1,'msg'=>'缺少参数')));
        $limit = 6;
        $start = ($page-1)*$limit; 
        $subQuery = M()->table(C('DB_PREFIX').'withdrawals a')->field('1 as type,a.user_id as user_id,a.create_time as time,a.money as money,a.status as status,a.bank_name as pay_type')
        ->union('select 2 as type,b.user_id as user_id,b.ctime as time,b.account as money,b.pay_status as status,b.pay_name as pay_type from '.C('DB_PREFIX').'recharge b')->buildSql();
        $result = M()->table($subQuery.'a')->where("a.user_id = {$user_id}")->order('time desc')->limit("{$start},{$limit}")->select();
        $weekarray = array("日","一","二","三","四","五","六");
        for($i = 0;$i<count($result);$i++){
            $result[$i]['week'] = "周".$weekarray[date('w',$result[$i]['time'])];
            $result[$i]['date'] = date('m-d',$result[$i]['time']);
        }
        if(empty($result))
            exit(json_encode(array('status'=>1,'msg'=>'空数据','result'=>$result)));
        else
            exit(json_encode(array('status'=>1,'msg'=>'获取成功','result'=>$result)));
    }

    /**
     * 选择充值方式
     */
    public function rechargeType(){       
        $paymentList = M('Plugin')->field('name,type,code,icon')->where("`type`='payment' and code != 'cod' and 
           status = 1 and  scene in(0,2)")->select();
        if(empty($paymentList)){
            exit(json_encode(array('status' =>'-1','msg'=>'数据为空')));
        }else{
            for($i = 0;$i < count($paymentList);$i++){
                $paymentList[$i]['image_url'] = "/plugins/".$paymentList[$i]['type']."/".$paymentList[$i]['code']."/".$paymentList[$i]['icon'];          
                unset($paymentList[$i]['type']);
                unset($paymentList[$i]['icon']);
            }
            exit(json_encode(array('status' => '1','msg' => '获取成功','result' => $paymentList)));
        }
    }
    //查询物流信息
    public function getExpressInfo(){
        $order_id = I('order_id', 0, 'intval');
        $order_info = M('order')->field('order_sn, shipping_status, shipping_code')->where(array('order_id'=>$order_id))->find();
        if($order_info['shipping_status'] == 0){
            $this->returnInfo(0, '暂无物流信息');
        }

        $result = getExpByJuhe($order_id);
        $this->returnInfo($result['status'], $result['msg'], $result['result']);
    }

    /**
     * 查询达达物流
     */
    public function getExpressInfoDaDa(){
        $order_id = I('order_id', 0, 'intval');
        $order_info = M('order')
            ->field('order_sn, shipping_status, shipping_code, shop_id,
            province, city, district, address, receiver_lng, receiver_lat')
            ->where(array('order_id'=>$order_id))->find();
        if($order_info['shipping_status'] == 0){
            $this->returnInfo(0, '暂无物流信息');
        }
        if($order_info['shipping_code'] == 'dada'){
            $app_key = tpCache('shopping.dd_app_key');
            $app_secret = tpCache('shopping.dd_app_secret');
            $source_id = tpCache('shopping.dd_source_id');

            if(!$app_key || !$app_secret ||!$source_id){
                $this->returnInfo(0, '系统参数异常');
            }

            $config['app_key'] = $app_key;
            $config['app_secret'] = $app_secret;
            $config['v'] = '1.0';
            $config['format'] = 'json';
            $is_test_dada = tpCache('shopping.dd_is_test');
            $config['source_id'] = $is_test_dada == 1 ? '73753' : $source_id;
            $config['host'] = 'http://newopen.qa.imdada.cn';

            $data['order_id'] = $order_info['order_sn'];
            $send_data['url'] = "/api/order/status/query";
            $send_data['businessParams'] = json_encode($data);

            $dada_client = new DadaRequestClient($config, $send_data);
            $resp = $dada_client->makeRequest();
            $resp = object_array($resp, true);
            if($resp['status'] == 'success'){
                $shop_info = M('shop')->where(array('id'=>$order_info['shop_id']))->find();
                $resp['result']['from'] = array(
                    'address'=>$shop_info['shop_address_city'].$shop_info['shop_address_street'],
                    'longitude'=>$shop_info['longitude'],
                    'latitude'=>$shop_info['latitude']
                );
                $region_list = get_region_list();
                $receiver_address = $region_list[$order_info['province']]['region_name'].$region_list[$order_info['city']]['region_name'].
                    $region_list[$order_info['district']]['region_name'].$order_info['address'];
                $resp['result']['to'] = array(
                    'address'=>$receiver_address,
                    'longitude'=>$order_info['receiver_lng'],
                    'latitude'=>$order_info['receiver_lat']
                );
                $this->returnInfo(1, '物流信息', $resp['result']);
            }else{
                $this->returnInfo(0, $resp['msg'], $resp['code']);
            }
        }else{

            $this->returnInfo(0, '暂无物流信息');
        }
    }
    /**
     * 用户充值
     */
    public function userRecharge(){
        if(!$this->user_id)
            exit(json_encode(array('status' => -1,'msg' => '缺少参数')));
        else{
            $user_info = M('users')->where(array('user_id'=>$this->user_id))->find(); //获取用户信息
			
            $data['user_id'] = $this->user_id;
            $data['nickname'] = $user_info['nickname'];
            $data['account'] = I('account');
            $data['order_sn'] = 'recharge'.get_rand_str(10,0,1);
            $data['ctime'] = time();
            $data['pay_code'] = I('pay_code');
			
            if (I('pay_code') == 'alipay') {
                $data['pay_name'] = 'app支付宝';
            } elseif (I('pay_code') == 'weixin') {
                $data['pay_name'] = '微信支付';
            } else {
                exit(json_encode(array('status' => -1,'msg' => '支付方式不正确!')));
            }
            $order_id = M('recharge')->add($data);
			// p($order_id);die;
            if($order_id){
                //直接跳转到支付宝支付
                if (I('pay_code') == 'alipay') {
                    $payment = R('Api/Payment/doRechangePay', array('order_id'=>$order_id));
                } elseif (I('pay_code') == 'weixin') {
                    $payment = R('Api/Wxpay/rechangePay', array('order_id'=>$order_id));
                }
            }else{
                exit(json_encode(array('status'=>-1, 'msg'=>'提交失败,参数有误!', 'result'=>'')));
            }
        }
    }


    ///////////////////////////////////////    定位  start     /////////////////////////////////////
    /***
     * 地址  省
     */
    public function getFirst(){
        $parent_id = I('parent_id');
        if($parent_id == 0){
            $first =  M('region2')->where('level=1')->select();
            $json_arr = json_encode(array('status'=>1,'msg'=>'获取成功','result'=>$first));
            exit($json_arr);
        }
    }


    /**
     * 地址  市辖区   县
     */
    public function getTwo(){
        $parent_id = I('id');
        if ($parent_id){
            $two = M('region2')->where("parent_id=$parent_id and level=2")->select();
            $json_arr = json_encode(array('status'=>1,'msg'=>'获取成功','result'=>$two));
            exit($json_arr);
        }
    }


    /**
     * 地址  街道
     */
   public function getThree(){
       $parent_id = I('id');
       $three = M('region2')->where("parent_id=$parent_id")->select();
       $json_arr = json_encode(array('status'=>1,'msg'=>'获取成功','result'=>$three));
       exit($json_arr);
   }
///////////////////////////////////////    定位  end     /////////////////////////////////////

    /**
     * 实名认证
     */
    public function certification()
    {
        if (!$this->user_id) return $this->returnInfo(-1, '请先登录');
        $username = I('username');//姓名
        if (empty($username))
            $this->returnInfo('-1','请填写您的真实姓名');
        if (!preg_match('/^[\x{4e00}-\x{9fa5}]+$/u',$username)) {
            $this->returnInfo('-1','您输入的姓名格式不正确,请输入身份证上的姓名');
        }
        $socialNo = I('card');//身份证号
        if (empty($socialNo))
            $this->returnInfo('-1','请填写您的身份证号码');
        if (!preg_match('/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/',$socialNo)){
            $this->returnInfo('-1','请填写正确的身份证号码');
        }

        if($_FILES)
        {
            $upload = new \Think\Upload();// 实例化上传类
            $upload->maxSize   =    $map['author'] = (1024*1024*3);// 设置附件上传大小 管理员10M  否则 3M
            $upload->exts      =     array('jpg', 'gif', 'png','jpeg');// 设置附件上传类型
            $upload->rootPath  =     './Public/upload/certification/'; // 设置附件上传根目录
            $upload->replace  =     true; // 存在同名文件是否是覆盖，默认为false
            //$upload->saveName  =   'file_'.$id; // 存在同名文件是否是覆盖，默认为false
            // 上传文件 
            $info   =   $upload->upload();  
            if(!$info) {// 上传错误提示错误信息
                return $this->returnInfo(-1, $upload->getError());
            }else{
                foreach ($info as $key => $value) {
                    if( !isset($data['szheng']) || $key == 'szheng' ) {
                        $data['szheng'] = $value['urlpath'];
                        continue;
                    }
                    if( !isset($data['zheng']) || $key == 'zheng' ) {
                        $data['zheng'] = $value['urlpath'];
                        continue;
                    }
                    if( !isset($data['fan']) || $key == 'fan' ) {
                        $data['fan'] = $value['urlpath'];
                        continue;
                    }                    
                }
            }
        }else{
            $this->returnInfo('-1','请上传证件照');  
        } 
        $data['user_id'] = $this->user_id;//用户id
        $data['username'] = $username;//姓名
        $data['card'] = $socialNo;//身份证号
        $data['status'] = 1;//状态
        $data['create_time'] = date('Y-m-d H:i:s');//创建时间
        $return = M('sm')->add($data);
        if ($return) {
            $this->returnInfo('1','实名认证资料上传成功',$return);
        } else {
            $this->returnInfo('-1','实名认证添加失败');
        }           
    } 


    public function certificationStatus(){
        $user_id = $this->user_id;
        $where['user_id'] = $user_id;
         //根据user_id查询数据，如果表中有数据，不让再次上传
        $sm = M('sm')->where($where)->find();
        $status = $sm['status'];
        if ($sm && $status == 1) {
            $this->returnInfo('1','正在审核','-1');
        } else if ($sm && $status == 3) {
            $concat = \tpCache('shop_info.phone');
            $this->returnInfo('1','您填写的认证信息书写不规范好有疑问请联系:'.$concat,'-2');
        }else if ($sm && $status == 2) {
            $this->returnInfo('1','您已通过审核','1');
        }else{
            $this->returnInfo('1','您还没有上传资料','-3');
        }
    }


    /**
    * 余额消费记录
    */
    public function auconch(){
        $token = I('token');
        $map['token'] = $token;
        $user_id = M('users')->field('user_id')->where($map)->find();
        $user_id = $user_id['user_id'];
        $auconch = M('account_log')->where("user_id=$user_id and user_money
            !=0")->field('user_id,user_money,change_time,desc')->select();
        $auconch?$auconch:[];
        if ($auconch) {
            $this->returnInfo('1','获取成功',$auconch);
        }else{
            $this->returnInfo('-1','获取成功',[]);
        }
    }

    /*
    *申请退款
    */
    public function addDrawback(){
        $rec_id = I('rec_id', '', 'trim');  //退款 订单商品id
        $order_id = I('order_id', 0, 'intval'); //退款 订单id

        $orderModel = M('order');
        $order_info = $orderModel->where(array('order_id'=>$order_id))->find();
        if(!$order_info || $order_info['user_id'] != $this->user_id){
            $this->returnInfo(0,'订单信息有误');
        }

        if(!in_array($order_info['order_status'], array(2,4)) || $order_info['confirm_time'] == 0 ){
            $this->returnInfo(0,'订单未签收');
        }
        $draw_day = $order_info['order_type'] == 1 ? tpCache('shopping.drawback_time_normal')
            : ($order_info['order_type'] == 2 ? tpCache('shopping.drawback_time_spec') : 0);

        if(!$draw_day || ($order_info['confirm_time'] + ($draw_day * 3600)) < time()){
            $this->returnInfo(0,'超出订单退款时限');
        }

        if(!$rec_id){
            $this->returnInfo(0,'订单商品参数有误');
        }

        $orderGoodsModel = M('order_goods');
        $rec_id_array = explode(',', $rec_id);
        if(!$rec_id_array){
            $this->returnInfo(0,'订单商品参数有误');
        }
        //退款 订单商品列表
        $order_goods_list = $orderGoodsModel->where(array('rec_id'=>array('in', $rec_id_array), 'order_id'=>$order_id))->select();
        //退款 订单商品id 与 实际查询数量是否一致
        if(count($rec_id_array) != count($order_goods_list)){
            $this->returnInfo(0,'订单商品参数有误');
        }

        //$order_goods_info = $orderGoodsModel->where(array('rec_id'=>$rec_id))->find();
        if(!$order_goods_list){
            $this->returnInfo(0,'订单商品参数有误');
        }
        if($order_info['is_drawback'] != 0){
            $this->returnInfo(0,'订单已申请过退款');
        }

        $money = 0;
        foreach($order_goods_list as $order_goods_info){
            if($order_goods_info['apply_return'] != 0){
                $renturn_info = '存在已申请售后商品，请勿重复提交';//$order_goods_info['apply_return'] == 1 ? '已申请售后，请等待审核' : '已申请售后';
                $this->returnInfo(0,$renturn_info);
                return;
            }
            //统计退款金额
            $money = bcadd($money, bcmul($order_goods_info['goods_num'], $order_goods_info['member_goods_price'], 2), 2);
        }

        /*$exp_no = I('exp_no', '', 'trim');
        if($order_info['order_type'] == 2 && !$exp_no){
            $this->returnInfo(0,'特殊商品订单退款,快递单号必填');
        }*/

        $urlpath = I("urlpath");    //图片路径
        if(is_array ($urlpath))
        {
            /*$upload_route = './Public/upload/drawback/';
            foreach($urlpath as $k => $v){
                $return = $this->base64_img_upload($v,$upload_route);
                if($return['status'] == 1){
                    $drawback_img[] = $return['url'];
                }
            }*/
            $add['img'] = serialize($urlpath);// 上传的图片文件
        }

        $add['user_id'] = $this->user_id;
        $add['order_id'] = $order_goods_info['order_id'];
        $add['back_reason'] = I('back_reason', '', 'trim');
        $add['content'] = I('content', '', 'trim');
        $now_time = time();
        $add['create_time'] = $now_time;


        $order_amount = $order_info['order_amount'];

        if($money > $order_amount){
            $money = $order_amount;
        }

        if($money <= 0){
            $this->returnInfo(-1,'退款金额异常');
        }

        $add['money'] = $money;
        $add['order_goods_id'] = $rec_id;

        if($order_info['order_type'] == 2){
            //$add['need_exp'] = 1;

            $add['shop_goods_type'] = 1;
            //$add['exp_fee'] = tpCache('shopping.drawback_exp_fee')?tpCache('shopping.drawback_exp_fee'):0;
        }else{
            $add['shop_goods_type'] = 0;
        }
        //$add['exp_no'] = $exp_no;
        $add['shop_id'] = $order_info['shop_id'];
        //自动审核通过时间
        $auto_drawback_date = tpCache('shopping.auto_drawback_date');
        $auto_drawback_time = 0;
        if($auto_drawback_date && $auto_drawback_date > 0){
            $auto_drawback_time = $now_time + $auto_drawback_date * 24 *3600;
        }
        $add['auto_time'] = $auto_drawback_time;
        //系统免运费数量
        $count_free_drawback_exp_fee = tpCache('shopping.count_free_drawback_exp_fee'); //平台免运费次数
        $drawbackModel = M('drawback');
        if($count_free_drawback_exp_fee > 0){

            $month_start_time = strtotime(date('Y-m-01').' 00:00:00');
            $where_count_free['shop_id'] = $order_info['shop_id'];
            $where_count_free['create_time'] = array('gt', $month_start_time);
            $where_count_free['is_free_exp_fee'] = 1;
            //该店铺本月申请退款免运费数量
            $count_drawback_exp_free = $drawbackModel->where($where_count_free)->count('id');
            if($count_free_drawback_exp_fee > $count_drawback_exp_free){
                $add['is_free_exp_fee'] = 1;
            }
        }

        //
        M()->startTrans();
        $add['out_refund_no'] = 'Draw'.get_rand_str(6,1,1);
        $row = $drawbackModel->add($add);
        if( !$row ) {
            M()->rollback();
            $this->returnInfo(-1,'申请失败');
        }
        $update_order_goods = $orderGoodsModel->where(array('rec_id'=>array('in', $rec_id_array)))
            ->setField('apply_return', 1);
        if( $update_order_goods === false)
        {
            M()->rollback();
            $this->returnInfo(-1,'订单商品操作失败');
        }

        $updateOrder['is_drawback'] = 1;
        $updateOrder['drawback_time'] = time();
        $update_order = $orderModel->where(array('order_id'=>$order_info['order_id']))->save($updateOrder);
        if($update_order === false){
            M()->rollback();
            $this->returnInfo(-2,'订单操作失败');
        }

        add_shop_message($order_info['shop_id'], '申请退款', '您有新的退款申请，请前往查看处理',1, $add['order_id']);

        M()->commit();

        $this->returnInfo(1,'操作成功', $row);
    }

    /*
     * 获取退款列表
     */
    public function getDrawbackList(){
        $order_id = I('order_id', 0, 'intval');
        if($order_id <= 0){
            $this->returnInfo(0,'订单信息有误');
        }
        $field = array('order_id', 'order_sn');
        $order_info = M('order')->field($field)->where(array('order_id'=>$order_id, 'user_id'=>$this->user_id))->find();
        if(!$order_info){
            $this->returnInfo(-1,'订单信息有误');
        }
        $fields_dra = array('ord_g.rec_id', 'ord_g.goods_num',
            'ord_g.member_goods_price','goods.goods_name','goods.goods_id','goods.market_price','goods.goods_remark'
            ,'goods.original_img'
        );

        $drawback_list = M('drawback')->field('id, status, img, back_reason, content, money, exp_fee, exp_no, 
            create_time, order_goods_id')
            ->where(array('order_id'=>$order_id))->order('id DESC')->select();
        $orderGoodsModel = M('order_goods');
        foreach($drawback_list as &$val){
            if($val['img']){
                $img_array = unserialize($val['img']);
                foreach($img_array as &$img_val){
                    $img_val = parseMediaUrl($img_val);
                }
                $val['img'] = $img_array;
            }
            $val['order_sn'] = $order_info['order_sn'];
            $val['create_time_show'] = date('Y-m-d', $val['create_time']);
            $val['cancel_btn'] = $val['status'] == 0 ? 1 : 0;
            $val['status_str'] = draw_status_user($val['status']);
            $money_amount = bcsub($val['money'], $val['exp_fee'], 2);
            $val['money_amount'] = $money_amount > 0 ? $money_amount : 0;
            $order_goods_list = $orderGoodsModel->alias('ord_g')
                ->field($fields_dra)
                ->join('ln_goods as goods ON ord_g.goods_id = goods.goods_id', 'left')
                ->where(array('ord_g.rec_id' => array('in', explode(',', $val['order_goods_id']))))
                ->select();
            foreach($order_goods_list as &$val2){
                $val2['original_img'] = parseMediaUrl($val2['original_img']);
            }
            $val['order_goods'] = $order_goods_list;
        }

        $this->returnInfo(1, '申请退款记录', $drawback_list);
    }

    /*
     * 获取退款列表
     */
    public function getDrawbackInfo(){
        $order_id = I('order_id', 0, 'intval');
        if($order_id <= 0){
            $this->returnInfo(0,'申请退款信息有误');
        }


        $drawback_info = M('drawback')->field('id, order_id, img, create_time, back_reason, content, money, status,
            shop_id,exp_code,
            update_time, order_goods_id, exp_fee, need_exp, exp_no, shop_goods_type')->where(array('order_id'=>$order_id))->find();
        if(!$drawback_info){
            $this->returnInfo(0,'申请退款信息有误');
        }
        if($drawback_info['img']){
            $img_array = unserialize($drawback_info['img']);
            foreach($img_array as &$img_val){
                $img_val = parseMediaUrl($img_val);
            }
            $drawback_info['img'] = $img_array;
        }

        $drawback_info['create_time_show'] = date('Y-m-d', $drawback_info['create_time']);
        $drawback_info['status_str'] = draw_status_user($drawback_info['status']);
        $drawback_info['cancel_btn'] = $drawback_info['status'] == 0 ? 1 : 0;
        $money_amount = bcsub($drawback_info['money'], $drawback_info['exp_fee'], 2);
        $drawback_info['money_amount'] = $money_amount > 0 ? $money_amount : 0;

        $fields_dra = array('ord_g.rec_id', 'ord_g.goods_num', 'ord_g.member_goods_price','goods.goods_name','goods.goods_id',
            'goods.market_price','goods.goods_remark','goods.original_img'
        );
        $order_goods_list = M('order_goods')->alias('ord_g')
            ->field($fields_dra)
            ->join('ln_goods as goods ON ord_g.goods_id = goods.goods_id')
            ->where(array('ord_g.rec_id'=>array('in', explode(',', $drawback_info['order_goods_id']))))
            ->select();

        foreach($order_goods_list as &$val){
            $val['original_img'] = parseMediaUrl($val['original_img']);
        }

        $drawback_info['order_goods'] = $order_goods_list;

        //shop_info
        $shop_info = M('shop')->where(array('id'=>$drawback_info['shop_id']))->find();
        $return_shop_info['shop_head_img'] = parseMediaUrl($shop_info['shop_head_img']);
        $return_shop_info['address'] = $shop_info['shop_address_city'].$shop_info['shop_address_street'].$shop_info['shop_name'];
        $return_shop_info['shop_user'] = $shop_info['shop_user'];
        $return_shop_info['shop_tel'] = $shop_info['shop_tel'];
        $drawback_info['shop_info'] = $return_shop_info;
        //shipping_info
        $shipping_list = M('plugin')->field('code, name')->where(array('type'=>'shipping'))->select();
        $drawback_info['shipping_list'] = $shipping_list;
        $this->returnInfo(1, '申请退款记录详情', $drawback_info);
    }
    /**
     * 获取订单商品详情
     */
    public function getOrderGoodsInfo(){
        $rec_id = I('rec_id', 0, 'intval');
        if($rec_id <= 0){
            $this->returnInfo(0, '订单商品参数有误');
        }
        $fields = array('rec_id', 'order_id', 'goods_id', 'goods_name', 'goods_num', 'market_price', 'member_goods_price',
            'apply_return', 'order_sn');
        $order_goods_info = M('order_goods')->field($fields)->where(array('rec_id'=>$rec_id))->find();
        if(!$order_goods_info){
            $this->returnInfo(0, '订单商品信息有误');
        }
        $goods_info = M('goods')->field('goods_remark, original_img')
            ->where(array('goods_id'=>$order_goods_info['goods_id']))
            ->find();
        $order_info = M('order')->field('order_type')->where(array('order_id'=>$order_goods_info['order_id']))->find();

        $order_goods_info['goods_remark'] = $goods_info['goods_remark'];
        $order_goods_info['original_img'] = parseMediaUrl($goods_info['original_img']);
        $order_goods_info['shop_goods_type'] = $order_info['order_type'] - 1;
        if($order_goods_info['shop_goods_type'] == 1){
            $exp_fee = tpCache('shopping.drawback_exp_fee');
        }else{
            $exp_fee = 0;
        }
        $order_goods_info['exp_fee'] = $exp_fee;
        $order_goods_info['goods_return_money'] = bcmul($order_goods_info['member_goods_price'], $order_goods_info['goods_num'], 2);
        $order_goods_info['return_amount'] = bcsub($order_goods_info['goods_return_money'], $exp_fee, 2);
        $order_goods_info['return_amount'] = $order_goods_info['return_amount'] > 0 ? $order_goods_info['return_amount'] : 0;
            $this->returnInfo(1, '订单商品信息', $order_goods_info);
    }

    /*
     * 撤销退款申请
     */
    public function cancel_drawback(){
        //申请退款数据id
        $id = I('id', 0, 'intval');
        if($id <= 0){
            $this->returnInfo(0, '申请退款参数有误');
        }
        $drawbackModel = M('drawback');
        $drwaback_info = $drawbackModel->field('status, order_id, order_goods_id')->where(array('id'=>$id, 'user_id'=>$this->user_id))->find();
        if(!$drwaback_info){
            $this->returnInfo(0, '申请退款信息不存在');
        }
        //只能撤销待审核状态数据
        if($drwaback_info['status'] != 0){
            $this->returnInfo(0, '申请退款已审核，无法撤销');
        }
        //修改订单状态
        //    1.除本条，该订单无其他申请    is_drawback => 0
        //    2.有其他申请，（1）都审核完成 is_drawback=>2 （2）有待审核 is_drawback=>1
        $order_drawback_list = $drawbackModel->field('status')
            ->where(array('id'=>array('neq', $id), 'order_id'=>$drwaback_info['order_id']))
            ->select();
        $orderModel = M('order');
        M()->startTrans();
        $is_success_order = true;
        if(count($order_drawback_list) == 0){
            //无其他申请
            $is_success_order = $orderModel->where(array('order_id'=>$drwaback_info['order_id']))->setField('is_drawback', 0);
        }else{
            $wait_deal_num = 0;
            foreach($order_drawback_list as $val){
                if($val['status'] == 0)
                    $wait_deal_num++;
            }
            if($wait_deal_num == 0){
                //有其他申请，（1）都审核完成
                $is_success_order = $orderModel->where(array('order_id'=>$drwaback_info['order_id']))->setField('is_drawback', 2);
            }
            //有其他申请，（2）有待审核 无需修改状态
        }
        if($is_success_order === false){
            M()->rollback();
            $this->returnInfo(0, '订单操作失败');
        }
        $is_success_order_goods = M('order_goods')->where(array('rec_id'=>array('in', explode(',', $drwaback_info['order_goods_id']))))
            ->setField('apply_return', 0);
        if($is_success_order_goods === false){
            M()->rollback();
            $this->returnInfo(0, '订单商品操作失败');
        }
        $is_success = $drawbackModel->where(array('id'=>$id))->delete();
        if($is_success === false){
            M()->rollback();
            $this->returnInfo(0, '申请撤销失败');
        }

        M()->commit();
        $this->returnInfo(1, '操作成功');

    }

    /**
     * 更新退款申请
     */
    public function update_drawback(){
        $id = I('id', 0, 'intval');
        if($id <= 0){
            $this->returnInfo(0,'申请退款信息有误');
        }
        $drawbackModel = M('drawback');
        $drawback_info = $drawbackModel->where(array('id'=>$id))->find();
        if(!$drawback_info){
            $this->returnInfo(0,'申请退款信息有误');
        }

        if($drawback_info['status'] != 1){
            $this->returnInfo(0,'申请退款状态有误');
        }

        if($drawback_info['send_time_end'] < time()){
            $this->returnInfo(0,'超出商品邮寄时限');
        }

        $exp_code = I('exp_code','', 'trim');
        if(!$exp_code){
            $this->returnInfo(0,'请选择快递公司');
        }
        $exp_no = I('exp_no','', 'trim');
        if(!$exp_no){
            $this->returnInfo(0,'请填写快递单号');
        }
        $update_drawback['exp_code'] = $exp_code;
        $update_drawback['exp_no'] = $exp_no;
        $update_drawback['status'] = 3;
        $update_drawback['send_time'] = time();
        $update_drawback['send_time_end'] = 0;

        $is_success = $drawbackModel->where(array('id'=>$id))->save($update_drawback);
        if($is_success === false){
            $this->returnInfo(0,'操作失败');
        }
        $this->returnInfo(0,'操作成功');
    }
}